package com.example.wanziyi

import android.content.Intent
import android.os.AsyncTask
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException


class MainActivity : AppCompatActivity() {
    private lateinit var minEditText: EditText
    private lateinit var maxEditText: EditText
    private lateinit var startButton: Button
    private lateinit var stopButton: Button
    private lateinit var progressTextView: TextView
    private lateinit var resultTextView: TextView
    private var isRunning = false
    private var primeList = mutableListOf<Int>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        title = "wanziyi 2022110544"

        minEditText = findViewById(R.id.minEditText)
        maxEditText = findViewById(R.id.maxEditText)
        startButton = findViewById(R.id.startButton)
        stopButton = findViewById(R.id.stopButton)
        progressTextView = findViewById(R.id.progressTextView)
        resultTextView = findViewById(R.id.resultTextView)

        // Load previously computed primes
        primeList = loadPrimes()

        startButton.setOnClickListener {
            val min = minEditText.text.toString().toIntOrNull()
            val max = maxEditText.text.toString().toIntOrNull()
            if (min != null && max != null && min <= max) {
                startButton.isEnabled = false
                stopButton.isEnabled = true
                isRunning = true
                PrimeTask().execute(min, max)
            } else {
                Toast.makeText(this, "Invalid input", Toast.LENGTH_SHORT).show()
            }
        }

        stopButton.setOnClickListener {
            isRunning = false
            stopButton.isEnabled = false
            startButton.isEnabled = true
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.history_menu_item) {
            val intent = Intent(this, HistoryActivity::class.java)
            startActivity(intent)
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    private inner class PrimeTask : AsyncTask<Int, Int, List<Int>>() {
        override fun doInBackground(vararg params: Int?): List<Int> {
            val min = params[0]!!
            val max = params[1]!!
            val primes = mutableListOf<Int>()
            for (i in min..max) {
                if (isPrime(i) && isRunning) {
                    publishProgress(i)
                    primes.add(i)
                } else if (!isRunning) {
                    break
                }
            }
            return primes
        }

        override fun onProgressUpdate(vararg values: Int?) {
            super.onProgressUpdate(*values)
            progressTextView.text = "Checking: ${values[0]}"
        }

        override fun onPostExecute(result: List<Int>) {
            super.onPostExecute(result)
            primeList.addAll(result)
            savePrimes(primeList)
            resultTextView.text = primeList.joinToString(", ")
            startButton.isEnabled = true
            stopButton.isEnabled = false
        }
    }

    private fun isPrime(num: Int): Boolean {
        if (num <= 1) return false
        for (i in 2..Math.sqrt(num.toDouble()).toInt()) {
            if (num % i == 0) return false
        }
        return true
    }

    private fun savePrimes(primeList: List<Int>) {
        val fos: FileOutputStream? = openFileOutput("primes.txt", MODE_PRIVATE)
        try {
            fos?.write(primeList.joinToString(", ").toByteArray())
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            fos?.close()
        }
    }

    private fun loadPrimes(): MutableList<Int> {
        val file = File(filesDir, "primes.txt")
        val primeList = mutableListOf<Int>()
        if (file.exists()) {
            try {
                val fis = FileInputStream(file)
                val data = fis.readBytes()
                primeList.addAll(data.toString().split(", ").map { it.toInt() })
                fis.close()
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return primeList
    }
}